<?php

class Domain_Magic
{
	
	/* 价格配置 */
	public function getConfig()
	{
		$key  = 'magic_con';
		$list = getcaches($key);
		if(!$list){
			$model = new Model_Magic();
			$list  = $model->getConfig();
			if($list){
				setcaches($key, $list);
			}
			
		}
		
		return $list;
	}
	
	/* 奖品规则 */
	public function getMagics()
	{
		$key  = 'magic';
		$list = getcaches($key);
		$list = null;
		if(!$list){
			$model = new Model_Magic();
			$list  = $model->getMagics();
			if($list){
				setcaches($key, $list);
			}
			
		}
		
		return $list;
	}
	
	
	/* 奖品列表 */
	public function getMagic($live_type)
	{
		//$domain   = new Domain_Live();
		//$giftlist = $domain->getGiftList($live_type);
		$model    = new Model_Magic();
		$giftlist = $model->getAllGift();
		$list     = $this->getMagics();
		foreach($list as $k => $v){
			unset($v['rate']);
			
			$needcoin = $v['needcoin'];
			$thumb    = '';
			$info     = [];
			foreach($giftlist as $k2 => $v2){
				if($v['giftid'] == $v2['id']){
					$v2['gifticon'] = get_upload_path($v2['gifticon']);
					// 整理
					$thumb    = $v2['gifticon'];
					//$needcoin = $needcoin ?: $v2['needcoin'];
					$info     = $v2;
					break;
				}
			}
			$all_type      = explode(',', $v['types']);
			$v['thumb']    = $thumb;
			$v['gift']     = $info;
			$v['needcoin'] = $needcoin;
			// 三个开关
			$v['is_common'] = in_array('common', $all_type) ? true : false;
			$v['is_high']   = in_array('high', $all_type) ? true : false;
			$v['is_luxury'] = in_array('luxury', $all_type) ? true : false;
			
			$list[$k] = $v;
		}
		
		// 重新整理
		/*$common = $high = $luxury = [];
		foreach($list as $item){
			$item['all_type'] = explode(',', $item['types']);
			if(in_array('common', $item['all_type'])){
				$common[] = $item;
			}
			if(in_array('high', $item['all_type'])){
				$high[] = $item;
			}
			if(in_array('luxury', $item['all_type'])){
				$luxury[] = $item;
			}
		}
		$all = ['luxury' => $luxury, 'high' => $high, 'common' => $common,];*/
		
		return $list;
	}
	
	
	/* 转奖 */
	public function turn($uid, $id, $liveuid, $stream, $times)  // , $itype
	{
		$rs        = array('code' => 0, 'msg' => '', 'info' => array());
		$magic_con = $this->getConfig();
		foreach($magic_con as $k => $v){
			if($v['id'] == $id){
				//$times  = $v['times'];
				$total  = $v['coin'];
				$ticket = $v['coupon'];
				$itype  = $v['itype'];
				break;
			}
		}
		if($times <= 0){
			$rs['code'] = 1002;
			$rs['msg']  = '信息错误';
			
			return $rs;
		}
		if(empty($total) || empty($ticket) || empty($itype)){
			$rs['code'] = 1002;
			$rs['msg']  = '信息错误';
			
			return $rs;
		}
		
		// 花费魔法券
		$ticket = $ticket * $times;
		$total  = $total * $times;
		if($ticket <= 0){
			$rs['code'] = 1002;
			$rs['msg']  = '信息错误';
			
			return $rs;
		}
		
		/* 更新用户余额 消费 */
		// 'consumption' => new NotORM_Literal("consumption + {$ticket}")
		$ifok = DI()->notorm->user
			->where('id = ? and magic_coupon >=?', $uid, $ticket)
			->update(array('magic_coupon' => new NotORM_Literal("magic_coupon - {$ticket}"),));
		if(!$ifok){
			$rs['code'] = 1001;
			$rs['msg']  = '余额不足';
			
			return $rs;
		}
		
		$showid = 0;
		if($stream != ''){
			$stream_a = explode('_', $stream);
			$showid   = isset($stream_a[1]) ? $stream_a[1] : 0;
		}
		
		$nowtime = time();
		//$insert  = array("type" => '0', "action" => '24', "uid" => $uid, "touid" => $uid, "giftid" => 0, "giftcount" => $times, "totalcoin" => $total, "addtime" => $nowtime);
		//DI()->notorm->user_coinrecord->insert($insert);
		
		$model = new Model_Magic();
		
		/* 召唤记录 */
		$insert2 = array("uid" => $uid, "liveuid" => $liveuid, "showid" => $showid, "itype" => $itype, "coin" => $total, "ticket" => $ticket, "nums" => $times, "addtime" => $nowtime);
		$log     = $model->setlog($insert2);
		$logid   = $log['id'];
		
		
		//$live_type   = getLiveType($liveuid, $stream);
		//$domain      = new Domain_Live();
		//$giftlist    = $domain->getGiftList($live_type);
		//$configpub   = getConfigPub();
		$giftlist = $model->getAllGift();
		$list     = $this->getMagics();
		$win_list = [];
		for($i = 0; $i < $times; $i++){
			// 大转盘的中奖
			//$win  = rand(1, 100 * 1000);
			//$rate = 0;
			// 组合中奖几率
			$luckRate1  = mt_rand(1, 1000);  // 随机概率：第一轮
			$luckRate2  = mt_rand(1, 100);   // 随机概率：第二轮
			$luckStart1 = 0;  // 第一轮中奖比率：开始数
			$luckStart2 = 0;  // 第二轮中奖比率：开始数
			foreach($list as $k => $v){
				if(!in_array($itype, $v['all_type'])){
					continue;
				}
				// 如果每个位置没有奖品 则这个位置不计算
				if(empty($v['giftid'])){
					continue;
				}
				// 比例
				// 如果获奖
				//$rate   += $v['rate'] * 1000;
				//$is_win = $win <= $rate;
				
				// 比例
				###########################################################################
				// 如果获奖 （这种比例适合与10w分之的低概率）
				$_giftRate = $v['rate'] * 1000;
				$is_win    = false;
				if($_giftRate < 1000){
					$luckEnd1 = $luckStart1 + $_giftRate;    // 第一轮中奖比率：结束数
					$luckEnd2 = $luckStart2 + 1;             // 第二轮中奖比率：结束数
					
					// 第一轮是否中奖
					// 第二轮是否中奖
					if(($luckRate1 > $luckStart1) && ($luckRate1 <= $luckEnd1)){
						if($luckRate2 == $luckEnd2){
							$is_win = true;
						}
					}
					
					// 如果不中奖 修改下一次的起始
					$luckStart1 = $luckEnd1;
					$luckStart2 = $luckEnd2;
				} else{
					$luckEnd1 = $luckStart1 + $_giftRate / 100;    // 第一轮中奖比率：结束数
					// 第一轮是否中奖
					if(($luckRate1 > $luckStart1) && ($luckRate1 <= $luckEnd1)){
						$is_win = true;
					}
					
					saveLog('开始：'.$luckStart1.'  结束：'.$luckEnd1.'  礼物：'.$_giftRate.'  随机数：'.$luckRate1);
					// 如果不中奖 修改下一次的起始
					$luckStart1 = $luckEnd1;
				}
				
				###########################################################################
				
				// 如果没有中奖 则直接结束 进行下一个礼物比对
				if(empty($is_win)){
					continue;
				}
				
				// 如果中奖  进行下一步操作
				// 如果获奖礼物已经存在
				if(isset($win_list[$v['id']])){
					$win_list[$v['id']]['nums']++;
					continue;
				}
				
				// 获奖礼物
				$data = [
					'id'       => $v['id'],
					'type'     => $itype,
					'giftid'   => $v['giftid'],
					'needcoin' => $v['needcoin'],
					'name'     => '',
					'thumb'    => '',
					'nums'     => '1',
				];
				foreach($giftlist as $k2 => $v2){
					if($v['giftid'] == $v2['id']){
						$data['name']  = $v2['giftname'];
						$data['thumb'] = $v2['gifticon'];
						/*if(empty($data['needcoin'])){
							$data['needcoin'] = $v2['needcoin'];
						}*/
					}
				}
				
				$win_list[$v['id']] = $data;
			}
		}
		
		$win_list = array_values($win_list);
		if($win_list){
			$model->uplogwin($logid, 1);
		}
		
		/* 写入中奖纪录 */
		$domain_pack = new Domain_Backpack();
		foreach($win_list as $k => $v){
			$data = [
				'logid'   => $logid,
				'uid'     => $uid,
				'type'    => $v['type'],
				'giftid'  => $v['giftid'],
				'nums'    => $v['nums'],
				'thumb'   => $v['thumb'],
				'addtime' => $nowtime,
			];
			
			$model->setWin($data);
			/* 礼物放进背包 */
			$domain_pack->addBackpack($uid, $v['giftid'], $v['nums']);
			
			
			$v['thumb'] = get_upload_path($v['thumb']);
			
			$win_list[$k] = $v;
		}
		
		/* 余额 */
		$userinfo2 = $this->getUserCoupon($uid);
		$userinfo  = getUserInfo($uid);
		
		$rs['info'][0]['coin']         = $userinfo2['coin'];
		$rs['info'][0]['magic_coupon'] = $userinfo2['magic_coupon'];
		$rs['info'][0]['level']        = $userinfo['level'];
		$rs['info'][0]['level_anchor'] = $userinfo['level_anchor'];
		$rs['info'][0]['user']         = $userinfo;
		$rs['info'][0]['list']         = $win_list;
		
		return $rs;
	}
	
	// 魔法券兑换
	public function coinToCoupon($uid, $coin, $coupon)
	{
		if(empty($uid)){
			$rs['code'] = 1001;
			$rs['msg']  = '请指定操作用户';
			
			return $rs;
		}
		
		/* 更新用户余额 消费 */
		// 增加用户魔法券数量
		$update = array(
			'coin'         => new NotORM_Literal("coin - {$coin}"),
			'consumption'  => new NotORM_Literal("consumption + {$coin}"),
			'magic_coupon' => new NotORM_Literal("magic_coupon + {$coupon}"),
		);
		$ifok   = DI()->notorm->user->where('id = ? and coin >=?', $uid, $coin)->update($update);
		if(!$ifok){
			$rs['code'] = 1001;
			$rs['msg']  = '余额不足';
			
			return $rs;
		}
		
		// 增加用户钻石变化记录
		$nowtime = time();
		$insert  = array("type" => '0', "action" => '24', "uid" => $uid, "touid" => $uid, "giftid" => 0, "giftcount" => 1, "totalcoin" => $coin, "addtime" => $nowtime);
		DI()->notorm->user_coinrecord->insert($insert);
		
		// 增加兑换记录
		$insert = array("uid" => $uid, "coin" => $coin, "coupon" => $coupon, "addtime" => $nowtime);
		DI()->notorm->magic_coupon->insert($insert);
		
		// 返回用户信息
		delcache("userinfo_".$uid);
		//$user = getUserInfo($uid);
		$user = DI()->notorm->user->select('id, coin,magic_coupon')->where('id=?', $uid)->fetchOne();
		
		return array('code' => 0, 'msg' => '', 'info' => $user);
	}
	
	// 获取用户的券
	public function getUserCoupon($uid)
	{
		return DI()->notorm->user->select('id,consumption,coin,magic_coupon')->where('id = ?', $uid)->fetchOne();
	}
	
	/* 用户中奖记录 */
	public function getWin($uid, $p, $pnum)
	{
		//$domain   = new Domain_Live();
		//$giftlist = $domain->getGiftList($live_type);
		$model    = new Model_Magic();
		$list     = $model->getWin($uid, $p, $pnum);
		$giftlist = $model->getAllGift();
		
		foreach($list as $k => $v){
			$thumb    = '';
			$giftname = '';
			foreach($giftlist as $k2 => $v2){
				if($v['giftid'] == $v2['id']){
					$thumb    = $v2['gifticon'];
					$giftname = $v2['giftname'];
					break;
				}
			}
			
			//$v['addtime'] = date('Y-m-d H:i', $v['addtime']);
			$v['thumb']    = get_upload_path($thumb);
			$v['giftname'] = $giftname;
			
			$list[$k] = $v;
		}
		
		return $list;
	}
	
	/* 最新中奖记录 */
	public function newWin($uid, $p, $pnum)
	{
		$model = new Model_Magic();
		
		return $model->getWinMagic($uid, $p, $pnum);
	}
	
	// 我的召唤记录
	public function myMagic($uid, $p, $pnum = 50)
	{
		$model = new Model_Magic();
		
		return $model->myMagic($uid, $p, $pnum);
	}
}


